(function ($) {
	// 请求方式
	var methods = {
		'getCache': 'get',
		'getLoading': 'get',
		'postLoading': 'post',
		'jsonLoading': 'post'
	}

	// form表单序列化JSON
	jQuery.fn.serializeJson = function () {
		var serializeObj = {};
		jQuery.each(this.serializeArray(), function () {
			if (serializeObj[this.name]) {
				if (jQuery.isArray(serializeObj[this.name])) {
					serializeObj[this.name].push(this.value);
				} else {
					serializeObj[this.name] = [serializeObj[this.name], this.value];
				}
			} else {
				serializeObj[this.name] = this.value;
			}
		});
		return serializeObj;
	};

	jQuery.each(['getCache', 'getLoading', 'postLoading', 'jsonLoading'], function (i, method) {
		jQuery[method] = function (url, data, success, fail, type) {
			var loadIndex = layer.msg('正在加载', {
				icon: 16,
				time: 0
			});
			// 如果第二个参数为函数，则移位
			if (jQuery.isFunction(data)) {
				type = fail;
				fail = success;
				success = data;
				data = undefined;
			}
			// 如果url 是DOM元素，则从里面获取url、data
			if (url instanceof Element) {
				data = $(url).serializeJson();
				url = $(url).attr('action');
			}

			// 如果是cache请求，就判断是否有缓存，如果有就尝试使用缓存
			if (method === 'getCache' && sessionStorage[url]) {
				var cacheData = undefined;
				try {
					cacheData = JSON.parse(sessionStorage[url])
				} catch (e) {
					console.error('request cache data is fail!', e)
				}

				if (cacheData) {
					if (jQuery.isFunction(success)) {
						success.call(this, cacheData);
					}

					return layer.close(loadIndex);
				} else {
					console.error('request cache data is fail!')
				}
			}

			return jQuery.ajax({
				url: url,
				traditional: true,
				type: type || methods[method],
				data: (method !== 'jsonLoading' ? data : JSON.stringify(data || {})),
				contentType: (method !== 'jsonLoading' ? undefined : "application/json; charset=utf-8"),
				success: function (result) {
					if (result.success) {
						if (method === 'getCache') {
							sessionStorage[url] = JSON.stringify(result);
						}

						if (jQuery.isFunction(success)) {
							success.call(this, result);
						}
					} else {
						layer.msg(result.msg || result.message || "未知", {
							icon: 2,
							time: 1500
						});

						if (jQuery.isFunction(fail)) {
							fail.call(this, result);
						}
					}
				},
				error: function (err) {
					layer.msg(err.statusText || "连接失败", {
						icon: 2,
						time: 1500
					});

					if (jQuery.isFunction(fail)) {
						fail.call(this, err);
					}
				},
				complete: function () {
					layer.close(loadIndex);
				}
			});
		};
	});
})(jQuery);